﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;

namespace QuanLyBanHang.SystemForms
{
    public partial class frmConfiguration : STLGROUP.Layers.Presentations.FormBase.frmBase
    {

        #region Variables

        private string _connectionString = "";
        private SqlConnection _sqlConnection = null;
        private SqlCommand _sqlCommand = null;
        private DataTable _dataTable = null;
        private string _path = Application.StartupPath + "\\QuanLyBanHang.exe.config";

        #endregion

        #region Constructors

        public frmConfiguration()
        {
            InitializeComponent();
        }

        #endregion

        #region Private Methods

        #region ConnectionString

        private string ConnectionString(string serverName, string databaseName)
        {
            return string.Format("server={0};database={1};Integrated Security=true;", serverName, databaseName);
        }

        private string ConnectionString(string serverName, string databaseName, string user, string password)
        {
            return string.Format("server={0};database={1};User Id={2};Password={3}", serverName, databaseName, user, password);
        }

        #endregion

        #region ConnectToServer

        private void ConnectToServer(string serverName)
        {
            _connectionString = ConnectionString(serverName, "master");
            _sqlConnection = new SqlConnection(_connectionString);
        }

        private void ConnectToServer(string serverName, string user, string password)
        {
            _connectionString = ConnectionString(serverName, "master", user, password);
            _sqlConnection = new SqlConnection(_connectionString);
        }

        #endregion

        #region GetDataTable

        private DataTable GetDataTable(string commandText)
        {
            DataTable dataTable = new DataTable();
            try
            {
                _sqlCommand = new SqlCommand();
                _sqlCommand.CommandText = commandText;
                _sqlCommand.Connection = _sqlConnection;
                SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(_sqlCommand);
                sqlDataAdapter.Fill(dataTable);

                return dataTable;
            }
            catch
            {
#if DEBUG
                //MessageBox.Show(ex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
#else
                if (rdoWindows.Checked)
                {
                    MessageBox.Show("Kết nối với máy chủ không thành công, vui lòng nhập lại địa chỉ máy chủ.", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    MessageBox.Show("Kết nối với máy chủ không thành công, vui lòng nhập lại địa chỉ máy chủ, tên đăng nhập và mật khẩu", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
#endif

            }
            return null;
        }

        #endregion

        #region AddItems

        private void AddItems(ComboBox cbo, DataTable dataTable)
        {
            try
            {
                cbo.DataSource = dataTable;
                cbo.DisplayMember = "name";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Lỗi");
            }
        }

        #endregion

        #region Connect

        private void Connect()
        {
            if (!string.IsNullOrEmpty(cbxServer.Text) && !string.IsNullOrEmpty(cbxDatabase.Text))
            {
                try
                {
                    string[] config1 = {string.Format(@"<?xml version=""1.0""?>
<configuration>
  <startup useLegacyV2RuntimeActivationPolicy=""true"">
    <supportedRuntime version=""v4.0"" sku="".NETFramework,Version=v4.0""/>
  </startup>
  <connectionStrings>    
    <add name=""QuanLyBanHangEntities"" connectionString=""metadata=res://*/DataAccessLayers.Data.csdl|res://*/DataAccessLayers.Data.ssdl|res://*/DataAccessLayers.Data.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source={0};Initial Catalog={1};Integrated Security=True;MultipleActiveResultSets=True&quot;"" providerName=""System.Data.EntityClient"" />
  </connectionStrings>
</configuration>",cbxServer.Text,cbxDatabase.Text)};

                    //<add name=""QuanLyBanHangEntities"" connectionString=""metadata=res://*/DataAccessLayers.QuanLyBanHang.csdl|res://*/DataAccessLayers.QuanLyBanHang.ssdl|res://*/DataAccessLayers.QuanLyBanHang.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source={0};Initial Catalog={1};Integrated Security=True;MultipleActiveResultSets=True&quot;"" providerName=""System.Data.EntityClient"" />

                    string[] config2 = {string.Format(@"<?xml version=""1.0""?>
<configuration>
  <startup useLegacyV2RuntimeActivationPolicy=""true"">
    <supportedRuntime version=""v4.0"" sku="".NETFramework,Version=v4.0""/>
  </startup>
  <connectionStrings>    
<add name=""QuanLyBanHangEntities"" connectionString=""metadata=res://*/DataAccessLayers.Data.csdl|res://*/DataAccessLayers.Data.ssdl|res://*/DataAccessLayers.Data.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source={0};Initial Catalog={1};User Id={2};Password ={3};MultipleActiveResultSets=True&quot;"" providerName=""System.Data.EntityClient"" />
  </connectionStrings>
</configuration>",cbxServer.Text,cbxDatabase.Text,cbxUserName.Text,txtPassword.Text)};

                    //<add name=""QuanLyBanHangEntities"" connectionString=""metadata=res://*/DataAccessLayers.QuanLyBanHang.csdl|res://*/DataAccessLayers.QuanLyBanHang.ssdl|res://*/DataAccessLayers.QuanLyBanHang.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source={0};Initial Catalog={1};User Id={2};Password={3};MultipleActiveResultSets=True&quot;"" providerName=""System.Data.EntityClient"" />
                    if (rdoWindows.Checked)
                    {
                        File.WriteAllLines(_path, config1);

                    }
                    else
                    {
                        File.WriteAllLines(_path, config2);
                    }

                    this.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Lỗi");
                }
            }
            else
            {
                MessageBox.Show("Vui lòng nhập địa chỉ máy chủ (Server) và tên cơ sở dữ liệu (Database).", "Lỗi");
            }
        }

        #endregion

        #region Server_Refresh

        private void Server_Refresh()
        {
            try
            {
                if (!string.IsNullOrEmpty(cbxServer.Text))
                {
                    if (rdoWindows.Checked)
                    {
                        ConnectToServer(Convert.ToString(cbxServer.Text));

                        _dataTable = GetDataTable("Select name From sysdatabases");
                        AddItems(cbxDatabase, _dataTable);
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(cbxUserName.Text) && !string.IsNullOrEmpty(txtPassword.Text))
                        {
                            ConnectToServer(Convert.ToString(cbxServer.Text), Convert.ToString(cbxUserName.Text), txtPassword.Text);

                            _dataTable = GetDataTable("Select name From sysdatabases");
                            AddItems(cbxDatabase, _dataTable);
                        }
                        else
                        {
                            _dataTable = null;
                            AddItems(cbxDatabase, _dataTable);
                            MessageBox.Show("Vui lòng nhập đầy đủ tên đăng nhập và mật khẩu", "Thông báo");
                        }
                    }
                }
                else
                {
                    _dataTable = null;
                    AddItems(cbxDatabase, _dataTable);
                    MessageBox.Show("Vui lòng nhập địa chỉ máy chủ (Server).", "Thông báo");
                }
                if (_dataTable == null)
                {
                    cbxServer.Enabled = true;
                    tlpServer.Enabled = true;
                }
                else
                {
                    cbxServer.Enabled = false;
                    tlpServer.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Lỗi");
                cbxServer.Enabled = true;
                tlpServer.Enabled = true;
            }
        }

        #endregion

        #endregion

        #region Events

        private void btxRefresh_Click(object sender, EventArgs e)
        {
            Server_Refresh();
        }

        private void btxConnect_Click(object sender, EventArgs e)
        {
            Connect();
            Application.Restart();
        }

        private void btxReset_Click(object sender, EventArgs e)
        {
            cbxServer.Text = cbxDatabase.Text = cbxUserName.Text = txtPassword.Text = string.Empty;
            Server_Refresh();
            cbxServer.Enabled = true;
        }

        private void btxExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btxRestore_Click(object sender, EventArgs e)
        {
            frmRestore frm = new frmRestore();
            frm.ShowDialog();
        }

        private void rdoWindows_CheckedChanged(object sender, EventArgs e)
        {
            tlpServer.Enabled = rdoSQL.Checked;
        }

        #endregion
    }
}
